/****************************************************
	文件：DownloadMgr.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/7/11 16:27:20
	功能：下载管理器
*****************************************************/

using System;
using System.Net;
using System.IO;
using System.Text;

namespace HTSpider
{
    public class DownloadMgr : Singleton<DownloadMgr>
    {
        public void Init() { }
        /// <summary>
        /// Http Get 方法
        /// </summary>
        /// <param name="url">URL链接</param>
        /// <param name="encoding">编码方式</param>
        /// <returns></returns>
        public string Get(string url, string encoding)
        {
            try
            {
                WebRequest webReq = WebRequest.Create(url);
                WebResponse webRsp = webReq.GetResponse();
                Stream rspStream = webRsp.GetResponseStream();
                using (StreamReader reader = new StreamReader(rspStream, Encoding.GetEncoding(encoding)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("GetHtml Error ! URL : {0}\nException : {1}", url, e.ToString());
                return string.Empty;
            }
        }
        /// <summary>
        /// Http Post 方法
        /// </summary>
        /// <param name="url">URL链接</param>
        /// <param name="postStr">上传的数据</param>
        /// <param name="encoding">编码方式</param>
        /// <returns></returns>
        public string Post(string url, string postStr, string encoding)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "post";
            req.Accept = "text/html, application/xhtml+xml, */*";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] buffer = Encoding.ASCII.GetBytes(postStr);
            req.ContentLength = buffer.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(buffer, 0, buffer.Length);
            }
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Stream rspstream = rsp.GetResponseStream();
            using (StreamReader reader = new StreamReader(rspstream, Encoding.GetEncoding(encoding)))
            {
                return reader.ReadToEnd();

            }
        }
    }
}
